package com.itheima.interceptor;

import com.itheima.constant.HttpStatus;
import com.itheima.exception.UserException;
import com.itheima.service.TokenService;
import com.itheima.vo.pojo.UmsAdmin;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * token过滤器
 */
//@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    //@DubboReference
    @Autowired
    private TokenService tokenService;

    //路径匹配器支持通配符
    private static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(!(handler instanceof HandlerMethod)){
            return true;    // 静态资源直接放行
        }

        //登录请求,放行
        String requestURI = request.getRequestURI();
        log.info("用户请求:{}",requestURI);
        if (PATH_MATCHER.match(requestURI,"/admin/login")){
            log.info("登录请求,放行");
            return true;
        }

        String token = tokenService.getToken(request);
        if(token == null || token.isEmpty()){        // token 是否为空
            System.out.println(token);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new UserException(HttpStatus.UNAUTHORIZED,"未登录,无权访问");
        }
        //获取用户信息
        UmsAdmin loginUser = tokenService.getLoginUser(request);
        try {
            if(loginUser==null){
                throw new UserException(HttpStatus.FORBIDDEN,"token已过期");
            }
                tokenService.verifyToken(loginUser);
                redisTemplate.expire(token,30, TimeUnit.MINUTES);
                return true;
            }catch(MalformedJwtException ex){
                throw new UserException("token 格式不对",ex,HttpStatus.FORBIDDEN);
            }catch(SignatureException ex){
                throw new UserException("token 不对",ex,HttpStatus.FORBIDDEN);
            }catch(ExpiredJwtException ex){
                throw new UserException("token已过期",ex,HttpStatus.FORBIDDEN);
            }


    }
}
